<?php
/**
 * 单品红包模块
 * User: Administrator
 * Date: 2019/12/5/005
 * Time: 15:17
 */

namespace app\service;


use think\Db;
use think\Exception;
use think\Log;

class GoodsSingleRedpacketService
{
    const GOODS_TABLE = 'goods';
    const GOODS_REDPACKET_TABLE = 'goods_redpacket';
    /**
     * 获取单品红包记录表的单条记录
     * @param array $condition  查询条件
     * @param string $field     查询字段
     */
    public function getGoodsRedPacketItem($condition = [],$field = '*')
    {
        return  Db::name(self::GOODS_REDPACKET_TABLE)->field($field)->where($condition)->find();
    }
    /**
     * 更新单品红包的数据
     * @param array $condition  更新条件
     * @param array $data       更新数据
     */
    public function updateExpireGoodsRedpacket($where = [],$data = [])
    {
        try{
            //查询当前 state=1【state==0,不需要查询和更改了】 & 即将到期
            $res = Db::name(self::GOODS_REDPACKET_TABLE)->where($where)->field('id,goods_id')->select();

            if (empty($res))    return  true;
            $goodsIds = array_column($res,'goods_id');
            $singleRedpacketIds = array_column($res,'id');

            Db::startTrans();
            $goodsCondition['goods_id'] = ['in',$goodsIds];
            $redpacketCondition['id']   = ['in',$singleRedpacketIds];
            //已过期的单品红包,更新商品表ds_goods中的： is_have_single_redpacket == 0
            $res_1 = Db::name(self::GOODS_TABLE)->where($goodsCondition)->update(['is_have_single_redpacket'=>0]);
            //已过期的单品红包,更新单品红包表 ds_goods_redpacket中的： state == 0不可用
            $res_2 = Db::name(self::GOODS_REDPACKET_TABLE)->where($redpacketCondition)->update(['state'=>0]);

            if($res_1 && $res_2) {
                Db::commit();
                Log::write(date('Y-m-d H:i:s')."--GoodsSingleRedpacketService/updateGoodsRedpacket：Result--[Sucess]");
            }else{
                Db::rollback();
                Log::write(date('Y-m-d H:i:s')."--GoodsSingleRedpacketService/updateGoodsRedpacket：Result--[Update Error]");
            }
        }catch (Exception $e){
            $msg = $e->getMessage();
            Log::write(date('Y-m-d H:i:s')."--GoodsSingleRedpacketService/updateGoodsRedpacket：Result--[$msg]");
        }

    }
}